<?php
require_once("../data/common.php");
if ($user->logged_in == FALSE) {
    die("Login first.");
}

function parseGPX($filename) {
    $data = array();

    $dom = new DOMDocument();
    $dom->loadXML(file_get_contents($filename));

    if (!$dom) {
            return $data;
    }

    $s = simplexml_import_dom($dom);
    foreach ( $s->trk->trkseg->trkpt as $item) {
        $point["lat"]= sprintf("%.4F", $item["lat"] );
        $point["lon"] = sprintf("%.4F", $item["lon"] );
        $point["time"] = gmdate( "Y-m-d H:i:s", strtotime( $item->time ) ); // hacky way to convert the date..
        $point["alt"] = $item->ele ? $item->ele : null;
        $point["speed"] = $item->speed ? $item->speed : null;
        $point["course"] = $item->course ? $item->course : null;
        $point["hdop"] = $item->hdop ? $item->hdop : null;
        array_push( $data, $point );
    }

    return $data;
}

if( ! isset( $_POST["upload"] ) ) {
    $template = new STE();
    $template->load("upload");
    $template->assign( array( "SELF" => "?page=upload" ) );
    print $template->display();
}
else {
    if( ! $_FILES["file"] || $_FILES["file"]["error"] > 0 ) {
        // some error happened when uploading
        //TODO create upload_failed (or even "failed" for general use?) template and use it
        die("error: " . $_FILES["file"]["error"] );
    }
    if( ! is_readable( $_FILES["file"]["tmp_name"] ) ) {
        // unable to read the temp file
        die("not readable");
    }
    /*if( $_FILES["file"]["size"] > MAX_FILE_SIZE ) {
        // too big file
    }*/

$newname = sprintf("%s/upload/%s", YOULOC_DATA, basename( $_FILES["file"]["tmp_name"] ) );

if( ! move_uploaded_file( $_FILES["file"]["tmp_name"], $newname ) ) {
    die( "unable to write the temporary file for upload" );
}
$points = parseGPX( $newname );
unlink( $newname );

try {
    $stmt = $dbh->prepare('INSERT INTO gps_data (user_id, device_id, lat, lon, time_received, speed, course, gps_time, gps_date, alt, hdop)
                                          VALUES(:uid, :devid, :lat, :lon, :time_received, :speed, :course, :gps_time, :gps_date, :alt, :hdop)');
    $dbh->beginTransaction();

    $devid = $_POST["devid"];

    $last_lat = -1;
    $last_lon = -1;
    $count = 0;
    foreach( $points as $point ) {
        if( $last_lat == $point['lat'] && $last_lon == $point['lon'] )
            continue;

        $last_lat = $point['lat'];
        $last_lon = $point['lon'];
        $stmt->bindParam( ':uid', $user->logged_in_user_id );
        $stmt->bindParam( ':devid', $devid );
        $stmt->bindParam( ':lat', $point['lat'] );
        $stmt->bindParam( ':lon', $point['lon'] );
        $stmt->bindParam( ':time_received', gmdate() ); // FIXME doesn't work..
        $stmt->bindParam( ':speed', $point['speed'] );
        $stmt->bindParam( ':course', $point['course'] );
        $stmt->bindParam( 'gps_time', $point['time'] );
        $stmt->bindParam( 'gps_date', $point['time'] );
        $stmt->bindParam( ':alt', $point['alt'] );
        $stmt->bindParam( ':hdop', $point['hdop'] );
        $stmt->execute();
        $count++;
    }
}
catch( PDOException $e ) {
    printf( "something bad happened, %s", $e->getMessage() );
    $stmt->rollback();
}

$last_one = $dbh->lastInsertId();
$first_one = $last_one - ( $count - 1 );

if( $dbh->commit() ) {
    printf("Imported %s points, adding track..", $count);
    try {
        $stmt = $dbh->prepare( "INSERT INTO tracks ( device_id, first_id, last_id, created ) VALUES( :devid, :first_id, :last_id, :created )" );
        $stmt->bindParam( ':devid', $devid );
        $stmt->bindParam( ':first_id', $first_one );
        $stmt->bindParam( ':last_id', $last_one );
        $stmt->bindParam( ':created', gmdate() ); // FIXME doesn't work
        $stmt->execute();
    }
    catch( PDOException $e ) {
        print "unable to add the track..";
    }
}
else {
    print "unable to commit";
}
}
